<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>反馈任务列表</span>
        <el-button class="button" @click="init" text>刷新</el-button>
      </div>
    </template>

    <!-- 表格 -->
    <el-table :data="tableData" height="550" style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column prop="rankId" label="预测AQI等级">
        <template #default="scope">
          <p v-if="scope.row.rankId == 1" style="color: #67c23a">优（一）</p>
          <p v-if="scope.row.rankId == 2" style="color: #ffff00">良好（二）</p>
          <p v-if="scope.row.rankId == 3" style="color: #ffa500">轻度污染（三）</p>
          <p v-if="scope.row.rankId == 4" style="color: #ff0000">中度污染（四）</p>
          <p v-if="scope.row.rankId == 5" style="color: #800080">重度污染（五）</p>
          <p v-if="scope.row.rankId == 6" style="color: #800000">严重污染（六）</p>
        </template>
      </el-table-column>
      <el-table-column prop="provience" label="省份">
        <template #default="scope">
          {{ scope.row.provience }}
        </template>
      </el-table-column>
      <el-table-column prop="airQualityId" label="空气质量id" v-if="false">
        <template #default="scope">
          {{ scope.row.airQualityId }}
        </template>
      </el-table-column>
      <el-table-column prop="city" label="城市">
        <template #default="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>

      <el-table-column prop="address" label="具体地址" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleEdit(scope.$index, scope.row)" :icon="Filter">去监测</el-button>
          <!-- <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button> -->

          <!-- 抽屉 -->
          <el-drawer ref="drawerRef" v-model="dialog" title="反馈任务详细信息" direction="rtl" class="demo-drawer">
            <div class="demo-drawer__content">
              <el-descriptions class="margin-top" :column="1" :size="size" border>
                <!-- <template #extra>
                        <el-button type="primary">Operation</el-button>
                    </template> -->
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon :style="iconStyle">
                        <user />
                      </el-icon>
                      反馈用户
                    </div>
                  </template>
                  <el-tag style="margin-right: 2px">{{ thisData.feedbackUserName }}</el-tag>
                  <!-- <el-tag style="margin-right: 2px;" v-if="scope.row.supervisor.sex == '0'">男</el-tag>
                                    <el-tag style="margin-right: 2px;" v-if="scope.row.supervisor.sex == '1'">女</el-tag> -->
                  <el-tag style="margin-right: 2px">{{ thisData.feedbackUserPhone }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon :style="iconStyle">
                        <Grid />
                      </el-icon>
                      网格
                    </div>
                  </template>
                  <el-tag style="margin-right: 2px">{{ thisData.provience }}</el-tag>
                  <el-tag style="margin-right: 2px">{{ thisData.city }}</el-tag>
                  <!-- <el-tag style="margin-right: 2px;">{{ scope.row.town.name }}</el-tag> -->
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon :style="iconStyle">
                        <location />
                      </el-icon>
                      详细地址
                    </div>
                  </template>
                  <el-tag style="margin-right: 2px">{{ thisData.address }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon :style="iconStyle">
                        <tickets />
                      </el-icon>
                      预估等级
                    </div>
                  </template>
                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="thisData.rankId == 1">一级</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="thisData.rankId == 2">二级</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="thisData.rankId == 3">三级</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="thisData.rankId == 4">四级</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="thisData.rankId == 5">五级</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="thisData.rankId == 6">六级</el-tag>

                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="thisData.rankId == 1">优</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="thisData.rankId == 2">良好</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="thisData.rankId == 3">轻度污染</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="thisData.rankId == 4">中度污染</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="thisData.rankId == 5">重度污染</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="thisData.rankId == 6">严重污染</el-tag>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>
                    <div class="cell-item">
                      <el-icon :style="iconStyle">
                        <ChatDotSquare />
                      </el-icon>
                      信息描述
                    </div>
                  </template>
                  <el-tag style="margin-right: 2px">{{ thisData.feedback }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="demo-drawer__content" style="margin-top: 20px">
              <el-form :model="form">
                <el-form-item label="SO₂浓度" :label-width="formLabelWidth">
                  <el-input v-model="form.so2Value" autocomplete="off" placeholder="请输入SO₂浓度" style="width: 150px" @input="SO2input" />ug/m3
                  <el-tag v-if="form.so2Level == '0'"></el-tag>
                  <el-tag effect="dark" color="#B0C4DE" class="tagclass" v-if="form.so2Level == -2">无数据</el-tag>
                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="form.so2Level == 1">一级</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="form.so2Level == 2">二级</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="form.so2Level == 3">三级</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="form.so2Level == 4">四级</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="form.so2Level == 5">五级</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="form.so2Level == 6">六级</el-tag>
                  <el-tag effect="dark" color="#00FFFF" class="tagclass" v-if="form.so2Level == -1">超出范围(0-2620)</el-tag>
                </el-form-item>
                <el-form-item label="CO浓度" :label-width="formLabelWidth">
                  <el-input v-model="form.coValue" autocomplete="off" placeholder="请输入CO浓度" style="width: 150px" @input="COinput" />ug/m3
                  <el-tag v-if="form.coLevel == '0'"></el-tag>
                  <el-tag effect="dark" color="#B0C4DE" class="tagclass" v-if="form.coLevel == -2">无数据</el-tag>
                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="form.coLevel == 1">一级</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="form.coLevel == 2">二级</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="form.coLevel == 3">三级</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="form.coLevel == 4">四级</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="form.coLevel == 5">五级</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="form.coLevel == 6">六级</el-tag>
                  <el-tag effect="dark" color="#00FFFF" class="tagclass" v-if="form.coLevel == -1">超出范围(0-60)</el-tag>
                </el-form-item>
                <el-form-item label="PM2.5浓度" :label-width="formLabelWidth">
                  <el-input v-model="form.spmValue" autocomplete="off" placeholder="请输入PM2.5浓度" style="width: 150px" @input="spminput" />ug/m3
                  <el-tag v-if="form.coLevel == '0'"></el-tag>
                  <el-tag effect="dark" color="#B0C4DE" class="tagclass" v-if="form.spmLevel == -2">无数据</el-tag>
                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="form.spmLevel == 1">一级</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="form.spmLevel == 2">二级</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="form.spmLevel == 3">三级</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="form.spmLevel == 4">四级</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="form.spmLevel == 5">五级</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="form.spmLevel == 6">六级</el-tag>
                  <el-tag effect="dark" color="#00FFFF" class="tagclass" v-if="form.spmLevel == -1">超出范围(0-500)</el-tag>
                </el-form-item>
                <el-form-item label="实测AQI等级" :label-width="formLabelWidth">
                  <el-tag v-if="form.aqiId == null">暂无实测等级</el-tag>
                  <el-tag effect="dark" color="#67C23A" class="tagclass" v-if="form.aqiId == '1'">一级 优</el-tag>
                  <el-tag effect="dark" color="#FFFF00" class="tagclass" v-if="form.aqiId == '2'">二级 良好</el-tag>
                  <el-tag effect="dark" color="#FFA500" class="tagclass" v-if="form.aqiId == '3'">三级 轻度污染</el-tag>
                  <el-tag effect="dark" color="#FF0000" class="tagclass" v-if="form.aqiId == '4'">四级 中度污染</el-tag>
                  <el-tag effect="dark" color="#800080" class="tagclass" v-if="form.aqiId == '5'">五级 重度污染</el-tag>
                  <el-tag effect="dark" color="#800000" class="tagclass" v-if="form.aqiId == '6'">六级 严重污染</el-tag>

                  <el-button type="danger" @click="calculateIAQI" style="margin-left: 20px">计算AQI</el-button>
                </el-form-item>
              </el-form>
              <div class="demo-drawer__footer" style="margin-left: 100px">
                <el-button type="primary" :loading="loading" @click="onSubmit">{{ loading ? '提交中 ...' : '提交实测数据' }}</el-button>
                <el-button @click="cancelForm">关闭</el-button>
              </div>
            </div>
          </el-drawer>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<!-- 知识点、技能 -->
<!-- 项目一：东软人口数据库管理系统 -->

<script setup>
import { ref, computed, onMounted } from 'vue'
import $axios from '../utils/axios'
import { Grid, Location, ChatDotSquare, Tickets, User, Filter } from '@element-plus/icons-vue'
import { ElDrawer, ElMessageBox, ElNotification } from 'element-plus'

const formLabelWidth = '130px'
let timer

const dialog = ref(false)
const loading = ref(false)

const form = ref({})
const thisData = ref({
  feedbackUserName: '',
  feedbackUserPhone: '',
  feedback: '',
  address: '',
  rankId: '',
  provience: '',
  city: ''
})
// 表格初始化
const tableData = ref([])
// const taskNums = ref(0)
// let isNotified = false; // 全局变量用于跟踪是否已经显示了消息提醒

// const gId = sessionStorage.getItem('id')
// let isNotified = sessionStorage.getItem('isNotified') === 'true' ? true : false;
// const init = async () => {
//     const path = '/feedback/findByGid/' + gId
//     const { data: res } = await $axios.get(path)
//     if (res.code === 200) {
//         tableData.value = res.result
//         taskNums.value = parseInt(res.msg)

//         if (!isNotified) {
//             ElNotification({
//                 title: '任务提醒',
//                 message: `您有 ${taskNums.value} 条未检测任务，请尽快处理!`,
//                 type: 'warning'
//             })
//             // 标记已经显示过消息提醒
//             isNotified = true; // 标记已经显示过消息提醒
//             sessionStorage.setItem('isNotified', 'true');
//         }
//     }
//     console.log(tableData.value);
// }
const gId = sessionStorage.getItem('userId')
const init = async () => {
  const path = '/api/investigator/airqualitylist'
  const response = await $axios.post(path, {
    id: gId
  })
  if (response.data.code === '200') {
    const { data } = response.data
    tableData.value = data
    //taskNums.value = parseInt(response.msg)

    // if (!isNotified) {
    //     ElNotification({
    //         title: '任务提醒',
    //         message: `您有 ${taskNums.value} 条未检测任务，请尽快处理!`,
    //         type: 'warning'
    //     })
    //     // 标记已经显示过消息提醒
    //     isNotified = true; // 标记已经显示过消息提醒
    //     sessionStorage.setItem('isNotified', 'true');
    // }
  }
  console.log(tableData.value)
}

onMounted(init)

const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 1 ? 'success-row' : ''
}

const updateTable = ref({})

//打开抽屉
const handleEdit = (index, row) => {
  dialog.value = true
  thisData.value.feedbackUserName = row.feedbackUserName
  thisData.value.feedbackUserPhone = row.feedbackUserPhone
  thisData.value.feedback = row.feedback
  thisData.value.address = row.address
  thisData.value.rankId = row.rankId
  thisData.value.provience = row.provience
  thisData.value.city = row.city
  form.value.airId = row.airQualityId
  console.log(thisData.value.city)
  //updateTable.value = row
  console.log(row.airQualityId)
  console.log(index, row, updateTable.value)
}

// const handleDelete = (index, row) => {
//     console.log(index, row)
// }

// 抽屉
const size = ref('')
const iconStyle = computed(() => {
  const marginMap = {
    large: '8px',
    default: '6px',
    small: '4px'
  }
  return {
    marginRight: marginMap[size.value] || marginMap.default
  }
})

// 从数据库获取判断条件判断污染物级别
const levelData = ref([
  {
    id: 1,
    iaqiMin: 0,
    iaqiMax: 50,
    so2Min: 0,
    so2Max: 50,
    coMin: 0,
    coMax: 3,
    spmMin: 0,
    spmMax: 35
  },
  {
    id: 2,
    iaqiMin: 50,
    iaqiMax: 100,
    so2Min: 50,
    so2Max: 150,
    coMin: 3,
    coMax: 5,
    spmMin: 35,
    spmMax: 75
  },
  {
    id: 3,
    iaqiMin: 100,
    iaqiMax: 150,
    so2Min: 150,
    so2Max: 475,
    coMin: 5,
    coMax: 15,
    spmMin: 75,
    spmMax: 115
  },
  {
    id: 4,
    iaqiMin: 150,
    iaqiMax: 200,
    so2Min: 475,
    so2Max: 800,
    coMin: 15,
    coMax: 25,
    spmMin: 115,
    spmMax: 150
  },
  {
    id: 5,
    iaqiMin: 200,
    iaqiMax: 300,
    so2Min: 800,
    so2Max: 1600,
    coMin: 25,
    coMax: 36,
    spmMin: 150,
    spmMax: 250
  },
  {
    id: 6,
    iaqiMin: 300,
    iaqiMax: 100000000,
    so2Min: 1600,
    so2Max: 2620,
    coMin: 36,
    coMax: 60,
    spmMin: 250,
    spmMax: 500
  }
])
// const level = async () => {
//     const path = '/aqi/findAll'
//     const { data: res } = await $axios.get(path)
//     if (res.code === 200) {
//         levelData.value = res.result
//     }
// }
// level()

const SO2input = () => {
  form.value.aqiId = null
  const value = parseFloat(form.value.so2Value)

  if (isNaN(value) || form.value.so2Value.trim() === '') {
    form.value.so2Level = -2 // 无数据
  } else if (value < 0 || value > 2620) {
    form.value.so2Level = -1 // 超出范围
  } else {
    for (let index = 0; index < levelData.value.length; index++) {
      if (form.value.so2Value >= levelData.value[index].so2Min && form.value.so2Value <= levelData.value[index].so2Max) {
        form.value.so2Level = levelData.value[index].id
      }
    }
  }
}

const COinput = () => {
  form.value.aqiId = null
  const value = parseFloat(form.value.coValue)

  if (isNaN(value) || form.value.coValue.trim() === '') {
    form.value.coLevel = -2 // 无数据
  } else if (value < 0 || value > 60) {
    form.value.coLevel = -1 // 超出范围
  } else {
    for (let index = 0; index < levelData.value.length; index++) {
      if (form.value.coValue >= levelData.value[index].coMin && form.value.coValue <= levelData.value[index].coMax) {
        form.value.coLevel = levelData.value[index].id
      }
    }
  }
}

const spminput = () => {
  form.value.aqiId = null
  const value = parseFloat(form.value.spmValue)

  if (isNaN(value) || form.value.spmValue.trim() === '') {
    form.value.spmLevel = -2 // 无数据
  } else if (value < 0 || value > 500) {
    form.value.spmLevel = -1 // 超出范围
  } else {
    for (let index = 0; index < levelData.value.length; index++) {
      if (form.value.spmValue >= levelData.value[index].spmMin && form.value.spmValue <= levelData.value[index].spmMax) {
        form.value.spmLevel = levelData.value[index].id
      }
    }
  }
}

// 计算IAQI
const calculateIAQI = () => {
  let IAQI = ''
  let so2IAQI = ''
  let coIAQI = ''
  let spmIAQI = ''
  for (let index = 0; index < levelData.value.length; index++) {
    if (form.value.so2Level === levelData.value[index].id) {
      let x = levelData.value[index].iaqiMax - levelData.value[index].iaqiMin //500-300
      let y = levelData.value[index].so2Max - levelData.value[index].so2Min //2620-1600
      let z = form.value.so2Value - levelData.value[index].so2Min //2000-1600
      so2IAQI = (x / y) * z + levelData.value[index].iaqiMin
      // console.log("so2IAQI:"+so2IAQI+" "+x+" "+y+" "+z);
    }
  }
  for (let index = 0; index < levelData.value.length; index++) {
    if (form.value.spmLevel === levelData.value[index].id) {
      let x = levelData.value[index].iaqiMax - levelData.value[index].iaqiMin
      let y = levelData.value[index].coMax - levelData.value[index].coMin
      let z = form.value.coValue - levelData.value[index].coMin
      coIAQI = (x / y) * z + levelData.value[index].iaqiMin
      // console.log("coIAQI:"+coIAQI+" "+x+" "+y+" "+z);
    }
  }
  for (let index = 0; index < levelData.value.length; index++) {
    if (form.value.spmLevel === levelData.value[index].id) {
      let x = levelData.value[index].iaqiMax - levelData.value[index].iaqiMin
      let y = levelData.value[index].spmMax - levelData.value[index].spmMin
      let z = form.value.spmValue - levelData.value[index].spmMin
      spmIAQI = (x / y) * z + levelData.value[index].iaqiMin
    }
  }

  IAQI = so2IAQI > coIAQI ? so2IAQI : coIAQI
  IAQI = IAQI > spmIAQI ? IAQI : spmIAQI

  for (let index = 0; index < levelData.value.length; index++) {
    if (IAQI > levelData.value[index].iaqiMin && IAQI <= levelData.value[index].iaqiMax) {
      form.value.aqiId = levelData.value[index].id
    }
  }
  if (form.value.so2Level <= 0 || form.value.coLevel <= 0 || form.value.spmLevel <= 0) {
    form.value.aqiId = null
  }
}

const updateGrid = ref({})
const drawerRef = ref(null)
const onSubmit = async () => {
  if (form.value.aqiId === null) {
    alert('数据有误，无法提交')
  } else {
    // console.log(tableData.value.id);
    //dateFormat()
    const path = '/api/investigator/airqualityinfo'

    const { data: res } = await $axios.post(path, {
      AQI: form.value.aqiId,
      airQualityId: form.value.airId,
      SO2Concentration: parseFloat(form.value.so2Value),
      COConcentration: parseFloat(form.value.coValue),
      PM25Concentration: parseFloat(form.value.spmValue)
    })
    //console.log(form.value)
    //drawerRef.value.close()
    cancelForm()
    init()
  }
}

const handleClose = (done) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('需要提交数据吗？')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 2000)
    })
    .catch(() => {
      // catch error
    })
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
  clearTimeout(timer)
}
</script>

<style scoped>
.box-card {
  width: 99%;
  height: 95%;
  margin-top: 12px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

/* .item {
    margin-bottom: 18px;
} */

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 5px;
}

.tagclass {
  margin-left: 5px;
  color: black;
  border: none;
}
</style>

<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
